/**
 * 
 */
package com.zc.BankCreditManagement.Servlet;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.gson.Gson;
import com.zc.BankCreditManagement.JavaBean.User;
import com.zc.BankCreditManagement.ServiceImpl.CustomerServiceImpl;
import com.zc.BankCreditManagement.ServiceImpl.ManagerServiceImpl;
import com.zc.BankCreditManagement.ServiceImpl.UserServiceImpl;
import com.zc.BankCreditManagement.ZCUtil.CodeProtect;

/**
 * @author ZhangCheng
 * @time 2019年9月19日
 */
@WebServlet("/LoginServlet")
public class LoginServlet extends HttpServlet {

	/**
	 * 一个特定标识符的序列号
	 */
	private static final long serialVersionUID = 2025214772822959313L;
	
	public LoginServlet(){
		super();
	}
	
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doPost(req, resp);
	}
	
	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		// TODO Auto-generated method stub
		String type = req.getParameter("Type");
		if("login".equals(type)) {
			loginCheck(req,resp);
		}else if("regiCheck".equals(type)){
			sendMsgToHTML(resp, regiCheck(req,resp));
		}else if("regiSetPWD".equals(type)){
			regiSetPWD(req,resp);
		}else if("forgetSetPWD".equals(type)) {
			forgetSetPWD(req,resp);
		}else if("useridCheck".equals(type)){
			userIdCheck(req,resp);
		}else if("emailCheck".equals(type)) {
			emailCheck(req,resp);
		}else if("logout".equals(type)){
			Cookie cookie = new Cookie("peoId",null);//cookie名字要相同
			cookie.setMaxAge(0);
            cookie.setPath(req.getContextPath());  // 相同路径
            resp.addCookie(cookie);
            resp.getWriter().write("Success");
//            Cookie[] cs = req.getCookies();//获取的是当前request请求的cookies
// 		   for(Cookie c : cs) {
//			   System.out.print(c.getName() +" +");
//			   System.out.print(c.getValue() + "\n");
//		   }
		}
	}
	private void emailCheck(HttpServletRequest req,HttpServletResponse resp) throws ServletException, IOException {
		String userId = req.getParameter("userId");
		String email = req.getParameter("email");
		CustomerServiceImpl cSI = new CustomerServiceImpl();
		String ret = cSI.verifyEmail(userId, email, true);
		System.out.println(ret);
		if(ret.split(" ")[0].equals("Success")) {
			resp.getWriter().write(ret.split(" ")[0]+" "+ret.split(" ")[1]);
		}else {
			resp.getWriter().write(ret);
		}
		
	}
	private void userIdCheck(HttpServletRequest req,HttpServletResponse resp) throws ServletException, IOException {
		String userId = req.getParameter("userId");
		UserServiceImpl uSI = new UserServiceImpl();
		if(uSI.getUserType(userId)!=-1) {
			resp.getWriter().write(userId);
		}else{
			resp.setCharacterEncoding("UTF-8");
			resp.getWriter().write("您输入的用户名不存在，请检查您是否修改过您的用户名或输入错误！");
		};
	}
	private void forgetSetPWD(HttpServletRequest req,HttpServletResponse resp) throws ServletException, IOException{
		String userid= req.getParameter("peoId");
		String newPwd = req.getParameter("pwd");
		UserServiceImpl uSI = new UserServiceImpl();
		if(uSI.resetPwdWithNewPwd(userid, newPwd)==1) {
			resp.setCharacterEncoding("UTF-8");
			resp.getWriter().write("Yes 修改成功，请牢记你的密码！");
		}else {
			resp.setCharacterEncoding("UTF-8");
			resp.getWriter().write("No 密码设置失败，请咨询客服后重试！");
		}
		
	}
	private void regiSetPWD(HttpServletRequest req,HttpServletResponse resp) throws ServletException, IOException{
		int peoId = Integer.parseInt(req.getParameter("peoId"));
		String pwd = req.getParameter("pwd");
		UserServiceImpl uSI = new UserServiceImpl();
		ManagerServiceImpl mSI =new ManagerServiceImpl();
		User u = new User(peoId+"", peoId, pwd, mSI.getThisInfoById(peoId, true) != null? 1 : 0);
		
		if(uSI.regiNewUser(u) == 1) {
			resp.setCharacterEncoding("UTF-8");
			resp.getWriter().write("Yes 注册成功，请牢记你的密码，您账户名是您的用户编号，账户名可在系统内修改1次！");
		}else {
			resp.setCharacterEncoding("UTF-8");
			resp.getWriter().write("No 密码设置失败，请咨询客服后重试！");
		}
	}
	private String regiCheck(HttpServletRequest req,HttpServletResponse resp) throws ServletException, IOException{
		
		int peoId = Integer.parseInt(req.getParameter("peoId"));
		UserServiceImpl uSI = new UserServiceImpl();
		if(uSI.getUserByPeoId(peoId)!=null) {
			return "您已经注册，请登录或找回密码！";
		}
		
		String email = req.getParameter("email");
		CustomerServiceImpl cSI = new CustomerServiceImpl();
		ManagerServiceImpl mSI = new ManagerServiceImpl();
		String cus = cSI.regiVerify(peoId, email);
		
		if(cus!=null) {
			return cus;
		}else {
			String man = mSI.regiVerify(peoId, email);
			if(man != null) {
				return man;
			}else {
				return "您输入的用户编号不存在，请检查后重试！";
			}
		}
		
		
	}
	/**
	 * 	登录请求的处理，判断用户名密码的合法性
	 * 之后将用户类型传递到前端并进行相应界面的显示
	 * 
	 */
	private void loginCheck(HttpServletRequest req,HttpServletResponse resp) throws ServletException, IOException{
		UserServiceImpl uSI = new UserServiceImpl();
		User u = uSI.isIdConnPWD(req.getParameter("userId"), req.getParameter("pwd"),true);
		if(u != null) {
			Cookie cookiepeoId = new Cookie(""
					+ "peoId", new CodeProtect().inCode(u.getPeoId()));
			resp.addCookie(cookiepeoId);
			if(u.getUserType() == 0) {
				resp.getWriter().write("Customer");
			}else if(u.getUserType() == 1) {
				resp.getWriter().write("Manager");
			}else {
				resp.getWriter().write("Admin");
			}
			
		}else {
			resp.getWriter().write("null");
		}
	};
	
	/**
	 * 	将对象包装成json格式给前端发送相应
	 */
	private void sendMsgToHTML(HttpServletResponse resp, Object obj) throws ServletException, IOException {
		Gson gson = new Gson();
		String msg = gson.toJson(obj);
		resp.setContentType("json/application;charset=UTF-8");
		resp.getWriter().write(msg);
	}
}
